package com.deer.wms.intercept.security;

import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * JWT 工具类
 *
 * @author : wei
 * @since : 2021-07-28 17:37:03
 **/
@Component
public class JwtUtil {
    //有效时长 (十五分钟)
    private static final long EXPIRATION = 100000L * 60 * 30;
    //刷新时间 (过期前五分钟，比如token有效期为：10:00~10:30，则在10:25分到10:30分内访问后台会自动刷新token)
    private static final long TOBE_EXPIRATION = 100000L * 60 * 20;
    //密钥(需要保密)
    public static final String TOKEN_SIGN_KEY = "EpicHust";
    //主题
    private static final String SUBJECT = "WMS";

    /**
     * 使用jwt生成token
     *
     * @param username 用户名
     */
    public String generateToken(String username) {
        String token = Jwts.builder()
                .setSubject(SUBJECT)
                .claim("username", username)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .signWith(SignatureAlgorithm.HS512, TOKEN_SIGN_KEY)
                .compressWith(CompressionCodecs.GZIP)
                .compact();

        return token;
    }

    /**
     * 解析token
     *
     * @param token
     */
    public static Claims parseJwt(String token) {
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(TOKEN_SIGN_KEY) // 设置标识名
                    .parseClaimsJws(token)  //解析token
                    .getBody();
        } catch (ExpiredJwtException e) {
            claims = e.getClaims();
        }
        return claims;
    }

    /**
     * 解析token获取用户
     */
    public String getUsername(String token) {
        Claims claims = parseJwt(token);
        return claims.get("username").toString();

    }

    /**
     * 是否过期
     *
     * @param token token
     */
    public static boolean isExpiration(String token) {
        Claims claims = parseJwt(token);
        System.out.println("过期时间: " + claims.getExpiration());
        return claims.getExpiration().before(new Date());
    }

    /**
     * 判断是否将要过期
     *
     * @param token
     */
    public static boolean isToBeExpiration(String token) {
        Claims claims = parseJwt(token);
        Date expiration = claims.getExpiration();
        Date tobeExpiration = new Date(System.currentTimeMillis() + TOBE_EXPIRATION);
        return expiration.before(tobeExpiration);
    }
}
